package org.example.thread.chapterIV;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 数据库连接池
 * 初始化连接池
 * 获取连接
 * 返回连接
 */
public class ConnectionPool {

    private static LinkedList<Connection> pool = new LinkedList<>();

    public ConnectionPool(int count) {
        for (int i = 0; i < count; i++) {
            pool.add(ConnectionDriver.initConnection());
        }
    }

    /**
     * 获取连接池
     *
     * @param mills 超时时间； mill <=0 : 不设置超时时间；
     * @return
     */
    public Connection getConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            // 不设置超时时间
            if (mills <= 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                // 到期时间
                long feature = System.currentTimeMillis() + mills;
                // 剩余的等待时间
                long remaining = mills;
                while (pool.isEmpty() && remaining > 0) {
                    pool.wait(remaining);
                    remaining = feature - System.currentTimeMillis();
                }
                Connection connection = null;
                if (!pool.isEmpty()) {
                    connection = pool.removeFirst();
                }
                return connection;
            }

        }
    }

    /**
     * 返回链接
     *
     * @param connection
     */
    public void releaseConnection(Connection connection) {
        synchronized (pool) {
            pool.addLast(connection);
            // 唤醒其他等待线程
            pool.notifyAll();
        }
    }
}
